package com.ruoyi.project.system.menu.service;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TreeUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.framework.web.domain.Ztree;
import com.ruoyi.project.system.menu.domain.Menu;
import com.ruoyi.project.system.menu.mapper.MenuMapper;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.role.domain.RoleMenu;
import com.ruoyi.project.system.role.mapper.RoleMenuMapper;
import com.ruoyi.project.system.third.domain.Third;
import com.ruoyi.project.system.third.service.ThirdService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.domain.UserMenu;
import com.ruoyi.project.system.user.mapper.UserMenuMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 *
 * @author ruoyi
 */
@Service
public class MenuServiceImpl implements IMenuService {
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private MenuMapper menuMapper;


    @Autowired
    private UserMenuMapper userMenuMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private ThirdService thirdService;

    /**
     * 根据用户查询菜单
     *
     * @param user 用户信息
     * @return 菜单列表
     */
    @Override
    public List<Menu> selectMenusByUser(User user) {
        Third third = thirdService.selectThirdAuth();
        boolean ssoSync = Objects.equals(third.getSsoSync(), 0);

        List<Menu> menus;
        // 管理员显示所有菜单信息
        if (user.isAdmin()) {
            menus = menuMapper.selectMenuNormalAll();
        } else if (ssoSync && StringUtils.isNotEmpty(user.getSt())) {
            if (CollectionUtils.isEmpty(user.getRoleKeys()) && user.getRoleKeys().contains("admin")) {
                menus = menuMapper.selectMenuNormalAll();
            } else if (CollectionUtils.isEmpty(user.getPermissionKeys())) {
                menus = Lists.newArrayList();
            } else {
                HashSet<String> menuPermsSet = new HashSet<>(user.getPermissionKeys());
                menus = menuMapper.selectMenuNormalAll();
                menus = menus.stream().filter(menu -> menuPermsSet.contains(menu.getPerms())).collect(Collectors.toList());
            }
        } else {
            menus = menuMapper.selectMenusByUserId(user.getUserId());
        }
        return TreeUtils.getChildPerms(menus, 0);
    }


    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    @Override
    public List<Menu> selectMenuList(Menu menu) {
        List<Menu> menuList;
        User user = ShiroUtils.getSysUser();
        if (user.isAdmin()) {
            menuList = menuMapper.selectMenuList(menu);
        } else if (CollectionUtils.isNotEmpty(user.getPermissionKeys())) {
            HashSet<String> menuPermsSet = new HashSet<>(user.getPermissionKeys());
            menuList = menuMapper.selectMenuNormalAll();
            menuList = menuList.stream().filter(curMenu -> menuPermsSet.contains(curMenu.getPerms()))
                    .filter(curMenu -> {
                        boolean result = true;
                        if (StringUtils.isBlank(menu.getMenuName())) {
                            result = StringUtils.contains(curMenu.getMenuName(), menu.getMenuName());
                        }

                        if (StringUtils.isBlank(menu.getVisible())) {
                            result = result && StringUtils.equals(curMenu.getVisible(), menu.getVisible());
                        }
                        return result;
                    }).collect(Collectors.toList());
        } else {
            menu.getParams().put("userId", user.getUserId());
            menuList = menuMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    @Override
    public List<Menu> selectMenuAll() {
        List<Menu> menuList;
        User user = ShiroUtils.getSysUser();
        if (user.isAdmin()) {
            menuList = menuMapper.selectMenuAll();
        } else if (CollectionUtils.isNotEmpty(user.getPermissionKeys())) {
            HashSet<String> menuPermsSet = new HashSet<>(user.getPermissionKeys());
            menuList = menuMapper.selectMenuNormalAll();
            menuList = menuList.stream().filter(curMenu -> menuPermsSet.contains(curMenu.getPerms()))
                    .collect(Collectors.toList());
        } else {
            menuList = menuMapper.selectMenuAllByUserId(user.getUserId());
        }
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询权限
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectPermsByRoleId(Long roleId) {
        List<String> perms = menuMapper.selectPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询菜单
     *
     * @param role 角色对象
     * @return 菜单列表
     */
    @Override
    public List<Ztree> roleMenuTreeData(Role role) {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<Menu> menuList = selectMenuAll();
        if (StringUtils.isNotNull(roleId)) {
            List<String> roleMenuList = menuMapper.selectMenuTree(roleId);
            ztrees = initZtree(menuList, roleMenuList, true);
        } else {
            ztrees = initZtree(menuList, null, true);
        }
        return ztrees;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param user 用户对象
     * @return 菜单列表
     */
    @Override
    public List<Ztree> userMenuTreeData(User user) {
        Long userId = user.getUserId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<Menu> menuList = selectMenuAll();
        if (StringUtils.isNotNull(userId)) {
            List<String> userMenuList = menuMapper.selectUserMenuTree(userId);
            ztrees = initZtree(menuList, userMenuList, true);
        } else {
            ztrees = initZtree(menuList, null, true);
        }
        return ztrees;
    }

    /**
     * 查询所有菜单
     *
     * @return 菜单列表
     */
    @Override
    public List<Ztree> menuTreeData() {
        List<Menu> menuList = selectMenuAll();
        List<Ztree> ztrees = initZtree(menuList);
        return ztrees;
    }

    /**
     * 查询系统所有权限
     *
     * @return 权限列表
     */
    @Override
    public LinkedHashMap<String, String> selectPermsAll() {
        LinkedHashMap<String, String> section = new LinkedHashMap<>();
        List<Menu> permissions = selectMenuAll();
        if (StringUtils.isNotEmpty(permissions)) {
            for (Menu menu : permissions) {
                section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms()));
            }
        }
        return section;
    }

    /**
     * 对象转菜单树
     *
     * @param menuList 菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Menu> menuList) {
        return initZtree(menuList, null, false);
    }

    /**
     * 对象转菜单树
     *
     * @param menuList     菜单列表
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag    是否需要显示权限标识
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Menu> menuList, List<String> roleMenuList, boolean permsFlag) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleMenuList);
        for (Menu menu : menuList) {
            Ztree ztree = new Ztree();
            ztree.setId(menu.getMenuId());
            ztree.setpId(menu.getParentId());
            ztree.setName(transMenuName(menu, permsFlag));
            ztree.setTitle(menu.getMenuName());
            if (isCheck) {
                ztree.setChecked(roleMenuList.contains(menu.getMenuId() + menu.getPerms()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

    public String transMenuName(Menu menu, boolean permsFlag) {
        StringBuffer sb = new StringBuffer();
        sb.append(menu.getMenuName());
        if (permsFlag) {
            sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</font>");
        }
        return sb.toString();
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Long menuId) {
        return menuMapper.deleteMenuById(menuId);
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public Menu selectMenuById(Long menuId) {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 查询子菜单数量
     *
     * @param parentId 菜单ID
     * @return 结果
     */
    @Override
    public int selectCountMenuByParentId(Long parentId) {
        return menuMapper.selectCountMenuByParentId(parentId);
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int selectCountRoleMenuByMenuId(Long menuId) {
        return roleMenuMapper.selectCountRoleMenuByMenuId(menuId);
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(Menu menu) {
        menu.setCreateBy(ShiroUtils.getLoginName());
        return menuMapper.insertMenu(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(Menu menu) {
        menu.setUpdateBy(ShiroUtils.getLoginName());
        return menuMapper.updateMenu(menu);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public boolean checkMenuNameUnique(Menu menu) {
        Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        Menu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
        if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int selectMenuCount(Menu menu) {
        return menuMapper.selectMenuCount(menu);
    }

    @Override
    public List<Menu> selectRecycleMenuList() {
        return menuMapper.selectRecycleMenuList();
    }

    @Override
    public List<UserMenu> selectRecycleMenuAccountList() {
        return userMenuMapper.selectRecycleMenuAccountList();
    }

    @Override
    public Set<String> selectPermsByRoleKeys(List<String> roleKeys) {
        List<String> perms = menuMapper.selectPermsByRoleKeys(roleKeys);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public Menu selectMenuByPerms(String perms) {
        return menuMapper.selectMenuByPerms(perms);
    }

    @Override
    public RoleMenu selectByRoleIdAndMenuId(Long roleId, Long menuId) {
        return roleMenuMapper.selectByRoleIdAndMenuId(roleId, menuId);
    }

    @Override
    public void deleteRoleMenu(RoleMenu roleMenu) {
        roleMenuMapper.delRoleMenu(roleMenu);
    }

    @Override
    public void clearUserMenu() {
        userMenuMapper.clearUserMenu();
    }

    @Override
    public int insertAuthUsers(Long menuId, String userIds) {
        Long[] users = Convert.toLongArray(userIds);
        // 新增用户与角色管理
        List<UserMenu> list = new ArrayList<>();
        for (Long userId : users) {
            UserMenu um = new UserMenu();
            um.setUserId(userId);
            um.setMenuId(menuId);
            list.add(um);
        }
        return userMenuMapper.batchUserMenu(list);
    }

    public int deleteAuthUsers(Long roleId, String userIds) {
        return userMenuMapper.deleteUserMenuInfos(roleId, Convert.toLongArray(userIds));
    }
}
